<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\service\business\Alone\Token\TokenService;
use app\admin\service\business\controllers\Auth\AuthService;
use app\admin\validate\Auth;
use think\facade\View;

class AuthController extends BaseController
{
    /** @var AuthService */
    protected $server;

    protected function initialize()
    {
        $this -> server = AuthService::getInstance();
    }

    /**
     * 后台登录
     *
     * @return object|string
     * @throws \Exception
     */
    public function login(){
        $tokenService = TokenService::getInstance();

        // 验证用户是否已登录
        if($tokenService -> getValue($tokenService -> get())) return redirect((string) url('/admin'));

        if($this -> request -> isPost()) {
            $params = $this -> request -> post(['username', 'password', 'code']);

            $this -> validate($params, Auth::class . '.login');

            $result = $this -> server -> login($tokenService, $params['username'], $params['password']);

            return $this -> returnData($result['code'], $result['msg'], $result['data']);
        }

        return View::fetch();
    }

    /**
     * 退出登录
     *
     * @return object
     */
    public function logout(){
        $this -> server -> logout(TokenService::getInstance());

        return $this -> returnData(200, '退出成功');
    }

    /**
     * 生成 token 令牌
     *
     * @return object
     */
    public function exchange(){
        return $this -> returnData(200, '请求成功', [
            'token' => $this -> request -> buildToken()
        ]);
    }
}
